package com.lcxsoft.userservice.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lcxsoft.commonutils.JwtUtils;
import com.lcxsoft.commonutils.MD5;
import com.lcxsoft.commonutils.Query;
import com.lcxsoft.commonutils.R;
import com.lcxsoft.feign.clients.SmsClient;
import com.lcxsoft.servicebase.exceptionhandler.FoodboxException;
import com.lcxsoft.userservice.entity.CustomUser;
import com.lcxsoft.userservice.mapper.CustomUserMapper;
import com.lcxsoft.userservice.query.UserQuery;
import com.lcxsoft.userservice.service.CustomUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lcxsoft.userservice.vo.UserVo;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author testjava
 * @since 2022-01-12
 */
@Service
public class CustomUserServiceImpl extends ServiceImpl<CustomUserMapper, CustomUser> implements CustomUserService {

    @Resource
    private CustomUserMapper customUserMapper;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public String login(String phone, String password) {
        if (StringUtils.isNullOrEmpty(phone)){
            throw new FoodboxException(20001, "手机号码不能为空");
        }
        CustomUser user = customUserMapper.selectOne(new LambdaQueryWrapper<CustomUser>().eq(CustomUser::getUserPhone, phone));
        //用户不存在
        if (user == null){
            throw new FoodboxException(20001, "用户不存在");
        }else {
            if (MD5.encrypt(password).equals(user.getUserPassword())){
                String jwtToken = JwtUtils.getJwtToken(user.getUserId(), user.getUserNickname());
                return jwtToken;
            }else {
                throw new FoodboxException(20001, "密码错误");
            }
        }
    }

    @Override
    public R register(UserQuery query) {
        String codeFromRedis = redisTemplate.opsForValue().get(query.getUserPhone());
        //验证码相同，允许注册
        if (query.getCode().equals(codeFromRedis)){
            //判断账号是否村存在
            CustomUser customUser = customUserMapper.selectOne(new LambdaQueryWrapper<CustomUser>().eq(CustomUser::getUserPhone, query.getUserPhone()));
            if (customUser == null){
                String dormitoryId = customUserMapper.selectDormitoryId(query.getUserSchool(), query.getUserBuliding(), query.getUserDormitory());
                CustomUser user = new CustomUser();
                BeanUtils.copyProperties(query, user);
                user.setUserId(UUID.randomUUID().toString());
                user.setUserPassword(MD5.encrypt(query.getUserPassword()));
                user.setUserDormitory(dormitoryId);
                user.setCreatetime(LocalDateTime.now());
                customUserMapper.insert(user);
            } else {
                return R.error().message("该手机号已经被注册");
            }
            return R.ok().message("注册成功");
        }else {
            return R.error().message("验证码错误");
        }
    }

    @Override
    public R findUserList(UserQuery query) {
        PageHelper.startPage(query.getCurrentPage(), query.getPageSize());
        List<UserVo> userVos = customUserMapper.selectUserList(query.getUserNickname());
        PageInfo<UserVo> pageInfo = new PageInfo<>(userVos);
        long total = pageInfo.getTotal();
        List<UserVo> list = pageInfo.getList();
        return R.ok().data("userList", list).data("total", total);
    }

    @Override
    public R todayNewRegister() {
        String morning = LocalDate.now().toString() + " 00:00:00";
        String night = LocalDate.now().toString() + " 23:59:59";
        Integer count = customUserMapper.countUserByTime(morning, night);
        return R.ok().data("todayUser", count);
    }
}
